/* 
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Project: MyMANET - A Platform to Build Customized MANET's
Developers: Ashwin Paranjpe, Santosh Vempala
Georgia Institute of Technology, Atlanta, USA
*/

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
    
#define BUFFER_LEN 512
#define NUM_OF_PACKETS 40
#define PORT 9931
    
 
int main(void)
{
	struct sockaddr_in si_me, si_other;
	int s, i, slen=sizeof(si_other);
	char buf[BUFFER_LEN];
	char msg[40]="";
	FILE *fp_command=NULL;
    
	if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
		perror("socket:");
		exit(1);
    	}

	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(PORT);
	si_me.sin_addr.s_addr = htonl(INADDR_ANY);
	
	if ((bind(s, (struct sockaddr *)&si_me, sizeof(si_me))) == -1){
		perror("bind:");
		exit(1);
    	}
	
	printf("\nPress Control-C to Abort\n");

	while(1){
		char command[50]="";
		char num_of_files[5]="";

		printf("\nWaiting for file requests from Clients...\n");
		if (recvfrom(s, buf, BUFFER_LEN, 0, (struct sockaddr *)&si_other, (int *)&slen)==-1){
			perror("recvfrom:");
			exit(1);
		}

		printf("Received file request from IP: %s Port:%d\nFile Name: %s\n\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
		system("rm -rf ./temp");
		system("mkdir ./temp");
		chdir("./temp/");
		sprintf(command, "split -d -b 10000 ../%s %s", buf, buf);
		system(command);
		sprintf(command, "ls | grep %s | wc -l", buf);
		fp_command = popen(command, "r");
		if (fp_command == NULL) {
			printf("Failed to run command. Have to Quit.\n" );
			exit(1);
		}
		if(fgets(num_of_files, sizeof(num_of_files)-1, fp_command) == NULL){
			perror("fgets");
		}
		pclose(fp_command);
		system("cp ./* /home/ashwin/tftpboot");
		system("chown nobody /home/ashwin/tftpboot/*");
		chdir("../");
		system("rm -rf ./temp");
	
		memset(buf, 0, BUFFER_LEN);
                sprintf(buf, "%s", num_of_files);

		//printf("Enter Msg for Client: ");
		//gets(msg);
                //sprintf(buf, "%s", msg);

		if (sendto(s, buf, BUFFER_LEN, 0, (struct sockaddr *)&si_other, slen)==-1){
                        perror("sendto()");
                        exit(1);
                }

	}
    
	close(s);
	return 0;
}

